#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>

#define FILE_PATH "students.dat"
#define NUM_STUDENTS 5
#define NAME_LEN 4

typedef struct {
    char name[NAME_LEN];
    int age;
} Student;

int main() {
    int fd;
    Student *students;
    const int size = NUM_STUDENTS * sizeof(Student);

    // 创建并调整文件大小
    if ((fd = open(FILE_PATH, O_RDWR | O_CREAT | O_TRUNC, 0666)) == -1) {
        perror("open failed");
        exit(EXIT_FAILURE);
    }
    ftruncate(fd, size);

    // 映射文件到内存
    students = (Student*)mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (students == MAP_FAILED) {
        perror("mmap failed");
        close(fd);
        exit(EXIT_FAILURE);
    }

    // 写入学生数据
    for (int i = 0; i < NUM_STUDENTS; i++) {
        snprintf(students[i].name, NAME_LEN, "S%d", i+1);
        students[i].age = 18 + i;
        printf("Write: %s %d\n", students[i].name, students[i].age);
    }

    // 清理资源
    munmap(students, size);
    close(fd);
    return 0;
}
